from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .ser import *
import re
import redis
from captcha.image import ImageCaptcha
import random, string
from django.http import HttpResponse
import jwt, datetime
from shop import settings


class CheckUsername(APIView):
    def get(self, request, username):
        if not re.findall(r'^[a-zA-Z][a-zA-Z0-9_]{4,15}$', username):
            return Response({
                'code': 400,
                'msg': '用户名格式错误'
            })
        if User.objects.filter(username=username):
            return Response({
                'code': 400,
                'msg': '用户名重复'
            })
        return Response({
            'code': 200,
            'msg': '用户名可用'
        })


class CheckMobile(APIView):
    def get(self, request, mobile):
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return Response({
                'code': 400,
                'msg': '手机号格式错误'
            })
        if User.objects.filter(mobile=mobile):
            return Response({
                'code': 400,
                'msg': '手机号重复'
            })
        return Response({
            'code': 200,
            'msg': '手机号可用'
        })


class Image_Code(APIView):
    def get(self, request, uuid):
        code = ''.join(random.sample(string.ascii_letters+string.digits, 4))
        img = ImageCaptcha()
        img_code = img.generate(code)
        res = redis.Redis(host='localhost', port=6379, db=1)
        res.set(str(uuid), code, ex=60)
        res.close()
        return HttpResponse(img_code, content_type='image/png')


class CheckCode(APIView):
    def post(self, request):
        uuid = request.data.get('imageCodeID')
        img_code = request.data.get('imageCode')
        res = redis.Redis(host='localhost', port=6379, db=1)
        res_code = res.get(uuid).decode()
        if not res_code:
            return Response({'code': 204, 'msg': '验证码过期'})
        if str(img_code).lower() == str(res_code).lower():
            return Response({'code': 200, 'msg': 'OK'})
        else:
            return Response({'code': 404, 'msg': '验证码错误'})


class Register(APIView):
    def post(self, request):
        username = request.data.get('userName')
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        agree = request.data.get('agree')
        if not all([username, pwd, mobile]):
            return Response({'code': 204, 'msg': '注册信息不完整'})
        if not agree:
            return Response({'code': 204, 'msg': '请同意用户协议'})
        User.objects.create_user(username=username, password=pwd, mobile=mobile)
        return Response({'code': 200, 'msg': '注册成功'})


def gen_token(user):
    payload = {
        'user_id': user.id,
        'username': user.username,
    }
    token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
    return token


class Login(APIView):
    def post(self, request):
        username = request.data.get('user')
        pwd = request.data.get('pwd')
        try:
            from django.db.models import Q
            user = User.objects.get(Q(username=username) | Q(mobile=username))
        except Exception as e:
            print(e)
            return Response({
                'code': 204,
                'msg': '用户不存在'
            })
        if not user.check_password(pwd):
            return Response({
                'code': 204,
                'msg': '用户名或密码不正确'
            })
        token = gen_token(user)
        return Response({
            'code': 200,
            'msg': '登录成功',
            'token': token,
            'user': {
                'userName': user.username,
                'uid': user.id,
            }
        })


class Logout(APIView):
    def get(self, request):
        return Response({
            'code': 200
        })


class UserCenter(APIView):
    def get(self, request):
        # 判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('user_id'))
        except Exception as e:
            print(e)
            return Response({'msg': '用户未登录', 'code': 204})

        # 返回前端需要的数据
        addrs_list = []

        # 查询用户地址
        addrs_data = user.addr_set.all()

        ser = AddrSer(addrs_data, many=True)
        # # 手动序列化
        # for i in addrs_data:
        #     addrs_list.append({
        #         'id': i.id,
        #         'receiver': i.receiver,
        #         'receiver_mobile': i.receiver_mobile,
        #         'receiver_addr': i.receiver_addr,
        #         'is_default': i.is_default,
        #     })
        return Response({'msg': 'OK', 'code': 200, 'userInfo': {
            'username': user.username,
            'phone': user.mobile,
            # 'addrs': addrs_list,
            'addrs': ser.data,
        }})

    def put(self, request):
        # 判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('user_id'))
        except Exception as e:
            print(e)
            return Response({'msg': '用户未登录', 'code': 204})

        # 获取前端数据
        phone = request.data.get('phone')
        addrs_list = request.data.get('addrs')

        # 修改用户手机号
        if not re.findall(r'^1[3-9]\d{9}$', phone):
            return Response({'msg': '手机号不符合规则', 'code': 204})
        user.mobile = phone
        user.save()

        # 修改地址，循环修改
        for i in addrs_list:
            Addr.objects.filter(id=i.get('id')).update(
                receiver=i.get('receiver'),
                receiver_mobile=i.get('receiver_mobile'),
                receiver_addr=i.get('receiver_addr'),
                is_default=i.get('is_default'),
            )
        return Response({'msg': '修改成功', 'code': 200})


class UserAddr(APIView):
    def get(self, request):
        # 判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('user_id'))
        except Exception as e:
            print(e)
            return Response({'msg': '用户未登录', 'code': 204})
        addrs_data = user.addr_set.all()
        ser = AddrSer(addrs_data, many=True)
        return Response({'msg': 'OK', 'code': 200, 'addrList': ser.data})


    def post(self, request):
        # 判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('user_id'))
        except Exception as e:
            print(e)
            return Response({'msg': '用户未登录', 'code': 204})
        receiver = request.data.get('receiver')
        receiver_mobile = request.data.get('receiver_mobile')
        receiver_addr = request.data.get('receiver_addr')
        is_default = request.data.get('is_default')
        if not all([receiver, receiver_addr, receiver_mobile]):
            return Response({'msg': '信息不完善', 'code': 204})
        if not re.findall(r'^1[3-9]\d{9}$', receiver_mobile):
            return Response({'msg': '手机号不符合规则', 'code': 204})

        if is_default:
            default_addr = Addr.objects.filter(user=user, is_default=True)
            default_addr.update(is_default=False)

        new_addr = Addr.objects.create(
            receiver=receiver,
            receiver_mobile=receiver_mobile,
            receiver_addr=receiver_addr,
            is_default=is_default,
            user=user
        )
        ser = AddrSer(new_addr)
        return Response({'msg': '添加成功', 'code': 200, 'addr': ser.data})

    def delete(self, request):
        # 判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('user_id'))
        except Exception as e:
            print(e)
            return Response({'msg': '用户未登录', 'code': 204})
        addr_id = request.data.get('addr_id')
        Addr.objects.filter(id=addr_id).delete()
        return Response({'msg': '删除成功', 'code': 200})


class UpdatePass(APIView):
    def put(self, request):
        # 判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('user_id'))
        except Exception as e:
            print(e)
            return Response({'msg': '用户未登录', 'code': 204})
        originPw = request.data.get('originPw')
        newPw = request.data.get('newPw')
        confirmNewPw = request.data.get('confirmNewPw')
        if not user.check_password(originPw):
            return Response({'msg': '原密码不正确', 'code': 204})
        if newPw != confirmNewPw:
            return Response({'msg': '密码不一致', 'code': 204})
        if originPw == newPw:
            return Response({'msg': '新密码与原密码相同', 'code': 204})
        user.set_password(newPw)
        user.save()
        return Response({'msg': '密码修改成功', 'code': 200})































